import {resolve} from 'path';
import {loadEnv} from 'vite';
import type {UserConfig, ConfigEnv} from 'vite';
import Vue from '@vitejs/plugin-vue';
import VueJsx from '@vitejs/plugin-vue-jsx';
import progress from 'vite-plugin-progress';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers';
import {createStyleImportPlugin, ElementPlusResolve} from 'vite-plugin-style-import';
import dts from 'vite-plugin-dts';

import {createProxy} from './proxy';

// https://vitejs.dev/config/
const root = process.cwd();

function pathResolve(dir: string) {
    return resolve(root, '.', dir);
}

export default ({command, mode}: ConfigEnv): UserConfig => {
    let env = {} as any;
    const isBuild = command === 'build';
    if (!isBuild) {
        env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root);
    } else {
        env = loadEnv(mode, root);
    }
    return {
        base: env.VITE_BASE_PATH,
        plugins: [
            Vue({
                script: {
                    // 开启defineModel
                    defineModel: true
                }
            }),
            VueJsx(),
            dts(),
            AutoImport({
                imports: ['vue'],
                dts: 'src/auto-import.d.ts',
                eslintrc: {
                    enabled: false,
                    filepath: './.eslintrc-auto-import.json',
                    globalsPropValue: true
                },
                resolvers: [ElementPlusResolver({importStyle: false})]
            }),
            Components({
                resolvers: [ElementPlusResolver()],
                dts: 'src/components.d.ts'
            }),
            progress(),
            env.VITE_USE_ALL_ELEMENT_PLUS_STYLE === 'false'
                ? createStyleImportPlugin({
                      resolves: [ElementPlusResolve()],
                      libs: [
                          {
                              libraryName: 'element-plus',
                              esModule: true,
                              resolveStyle: (name) => {
                                  if (name === 'click-outside') {
                                      return '';
                                  }
                                  return `element-plus/es/components/${name.replace(/^el-/, '')}/style/css`;
                              }
                          }
                      ]
                  })
                : undefined
        ],
        css: {
            preprocessorOptions: {
                less: {
                    javascriptEnabled: true
                }
            }
        },
        resolve: {
            extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css'],
            alias: [
                {
                    find: /\@\//,
                    replacement: `${pathResolve('src')}/`
                }
            ]
        },
        esbuild: {
            pure: env.VITE_DROP_CONSOLE === 'true' ? ['console.log'] : undefined,
            drop: env.VITE_DROP_DEBUGGER === 'true' ? ['debugger'] : undefined
        },
        build: {
            target: 'es2015',
            outDir: env.VITE_OUT_DIR || 'dist',
            lib: {
                entry: ['src/index.ts'],
                name: 'report-core',
                formats: ['es', 'cjs'],
                fileName: (format, entryName) => `${entryName}.${format}.js`
            },
            rollupOptions: {
                external: ['vue', 'lodash-es']
            }
        },
        server: {
            // 局域网访问
            host: true,
            // 启动端口
            port: env.VITE_PORT,
            // 启动时打开浏览器
            open: env.VITE_OPEN_BROWSER === 'true',
            // 跨域代理配置
            proxy: env.VITE_PROXY ? createProxy(JSON.parse(env.VITE_PROXY)) : undefined,
            hmr: {
                overlay: false
            }
        }
    };
};
